<?php

namespace App\Service\Cruise\Check;

use App\Exceptions\Custom\ResponseHttpException;
use App\Library\Rms\RmsShopApi;
use App\Library\Rms\RmsUserApi;
use App\Models\Cruise\CruiseCheckAlbumModel;
use App\Models\Cruise\CruiseCheckCompanyModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\File\FileProcessingModel;
use App\Models\Shop\ShopModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\BaseService;
use App\Service\OpenShop\User\RmsUserService;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use OSS\Core\OssException;

class CruiseCheckAlbumService extends BaseService
{

    /**
     * 稽核文件上传
     * @throws GuzzleException
     * @throws OssException
     */
    public static function uploadAlbum($cruiseOrderId, $type, $file, $relationId, $module, $authInfo, $address = '', $isAlbum = 1)
    {
        try {
            $oss = [];
            switch ($module) {
                case CruiseOrderModel::TYPE_CHECK:
                    $shopInfo = ShopModel::query()
                        ->where('id', $relationId)
                        ->select(['shopCode', 'address'])
                        ->first();
                    $info = $shopInfo->shopCode;

                    // 获得地址
                    if (!strlen($address)) {
                        $address = $shopInfo->address;
                    }

                    break;
                case CruiseOrderModel::TYPE_COMPANY_CHECK:
                    $info = object_get(CruiseCheckCompanyModel::query()->with('fsCompanyRel')->find($relationId), 'fsCompanyRel.name', '-');
                    break;
                default:
                    $info = '';
            }
            $userName = (new RmsUserApi())->getUserInfoByIds([$authInfo['userId']])['data'][0]['username'] ?? '';

            if (!$info || !mb_strlen($userName)) {
                self::throwErr('获取稽核信息或用户信息失败');
            }

            switch ($type) {
                case CruiseCheckAlbumModel::TYPE_VIDEO: //视频
                    CruiseCheckFileDisposeService::getVideoWatermark($cruiseOrderId, $file, $relationId, $info, $userName, $address, $module, $isAlbum);
                    $oss = [
                        'url' => $file
                    ];
                    break;
                case CruiseCheckAlbumModel::TYPE_IMAGE: //图片
                    // 添加任务文件处理结果
                    FileProcessingModel::query()
                        ->insert([
                            'type'           => FileProcessingModel::TYPE_IMAGE,
                            'processingType' => FileProcessingModel::PROCESSING_TYPE_WATERMARK,
                            'beforeUri'      => ltrim(parse_url($file, PHP_URL_PATH), '/'),
                            'afterUri'       => '',
                            'status'         => FileProcessingModel::STATUS_DEFAULT,
                            'createdAt'      => time(),
                            'createdByUid'   => $authInfo['userId'],
                            'updatedAt'      => time(),
                            'updatedByUid'   => $authInfo['userId'],
                        ]);

                    $oss = CruiseCheckFileDisposeService::getFileWatermark($file, $info, $userName, $address, $module);

                    FileProcessingModel::query()
                        ->updateOrCreate([
                            'type'           => FileProcessingModel::TYPE_IMAGE,
                            'processingType' => FileProcessingModel::PROCESSING_TYPE_WATERMARK,
                            'beforeUri'      => ltrim(parse_url($file, PHP_URL_PATH), '/'),
                        ], [
                            'afterUri'  => $oss['path'],
                            'status'    => FileProcessingModel::STATUS_FINISH,
                            'updatedAt' => time(),
                        ]);


                    if ($isAlbum) {
                        CruiseCheckAlbumModel::query()->create([
                            'type'       => CruiseCheckAlbumModel::TYPE_IMAGE,
                            'url'        => $oss['path'],
                            'relationId' => $relationId,
                            'cruiseOrderId' => $cruiseOrderId,
                            'status'     => CruiseCheckAlbumModel::STATUS_UNUSED,
                            'module'     => $module,
                        ]);
                    }
                    break;
                default:
                    self::throwErr('未定义的文件类型');
            }
            return $oss;
        } catch (\Exception $exception) {
            switch ($type) {
                case CruiseCheckAlbumModel::TYPE_VIDEO: //视频
                    $typeName = '视频';
                    break;
                case CruiseCheckAlbumModel::TYPE_IMAGE: //图片
                    $typeName = '图片';
                    break;
                default:
                    $typeName = '';
            }
            self::throwErr($typeName. '上传失败');
        }
    }

    /**
     * 获得稽核相册列表
     * @param $cruiseOrderId
     * @param $relationId
     * @param $status
     * @param $module
     * @return array
     */
    public static function list($cruiseOrderId, $relationId, $status, $module): array
    {
        $list = CruiseCheckAlbumModel::query()
            ->where('relationId', $relationId)
            ->where('cruiseOrderId', $cruiseOrderId)
            ->where('module', $module)
            ->when(mb_strlen($status), function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->where('createdAt', '>', Carbon::now()->subDays(30)->timestamp)//30天以外的已使用和未使用图片不显示
            ->orderByDesc('status')
            ->orderByDesc('updatedAt')
            ->get()
            ->map(function (CruiseCheckAlbumModel $albumModel) {
                return [
                    'url'     => picturePath($albumModel->url),
                    'path'    => $albumModel->url,
                    'isVideo' => $albumModel->type == CruiseCheckAlbumModel::TYPE_VIDEO,
                    'isUsed'  => $albumModel->status == CruiseCheckAlbumModel::STATUS_USED,
                ];
            })->toArray();
        return [
            'list' => $list
        ];
    }
}
